<template>
  <div>
    <scroll-view
      class="nearby-list"
      :scroll-y="true"
      @scrolltolower="handleNearbyListNextPage"
    >
      <block v-if="tableData.length > 0">
        <view
          v-for="item in tableData"
          :key="item.id"
          class="nearby-list-item"
          @click="handleChangeCurrentNearby(item)"
        >
          <view class="nearby-list-item-left">
            <view class="left-title">{{ item.title }}</view>
            <view class="left-content">{{ item.address }}</view>
          </view>
          <view class="nearby-list-item-right">
            <u-radio-group
              v-model="currentNearbyId"
              @change="handleChangeCurrentNearby(item)"
            >
              <u-radio :activeColor="themeColor" :name="item.id"></u-radio>
            </u-radio-group>
          </view>
        </view>
      </block>
    </scroll-view>
  </div>
</template>

<script>
import { mapState } from "@dcloudio/vue-cli-plugin-uni/packages/vuex3/dist/vuex.common";
import { TENCENT_MAP_KEY } from "@/const/address/key";

export default {
  name: "nearbyList",
  props: {
    params: {
      type: Object,
      default: () => {},
    },
    currentId: {
      type: String,
      default: "0",
    },
  },
  computed: {
    ...mapState("sp-common/user", ["location"]),
    ...mapState("sp-common/base", ["themeColor"]),
  },
  watch: {
    currentId(val) {
      if (val) {
        this.currentNearbyId = val;
      }
    },
  },
  created() {
    this.currentNearbyId = this.currentId;
  },
  mounted() {
    this.handleGetNearbyLocation(true);
    if (this.params?.keyword?.value) {
      this.handleSearchNearbyKeys(true, this.params.keyword);
    } else {
      this.handleSearchNearbyList(true);
    }
  },
  data() {
    return {
      tableData: [],
      currentNearbyId: 0,
      region: "",
    };
  },
  methods: {
    handleNearbyListNextPage() {
      this.$emit("next-page");
    },
    handleChangeCurrentNearby(item) {
      this.$emit("handleUpdateCurrentId", item);
      this.$nextTick(() => {
        this.$Router.back();
      });
    },
    handleGetNearbyLocation(isFirst = true) {
      if (!this.params) return;
      const { latitude = 0, longitude = 0 } = this.params;
      uni.request({
        url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${latitude},${longitude}&key=${TENCENT_MAP_KEY}`,
        success: (res) => {
          const {
            statusCode,
            data: {
              status,
              result: {
                address_reference: { landmark_l2 },
                ad_info: { city },
                address,
              },
            },
          } = res;
          if (statusCode === 200 && status === 0) {
            if (isFirst) {
              this.$emit("update:currentId", landmark_l2.id);
            }
            this.$emit("update:region", city);
            const params = {
              latitude: this.params.latitude,
              longitude: this.params.longitude,
              address,
              title: landmark_l2.title,
              distance: landmark_l2._distance,
            };
            this.$store.dispatch(
              "sp-address/location/setCurrentLocation",
              params
            );
            this.$emit("handleSetCover", {
              id: Number(landmark_l2.id),
              strId: landmark_l2.id,
              latitude: this.params.latitude,
              longitude: this.params.longitude,
              iconPath: "/static/images/address-1.png",
              width: 25,
              height: 25,
              callout: {
                content: landmark_l2.title,
                color: "#888888",
                fontSize: 14,
                display: "ALWAYS",
                bgColor: "#fff",
                padding: 10,
              },
            });
          }
        },
      });
    },
    handleSearchNearbyList(isClear = false) {
      if (!this.params) return;
      const {
        page_size,
        page_index,
        latitude = 0,
        longitude = 0,
      } = this.params;
      uni.request({
        url: `https://apis.map.qq.com/ws/place/v1/search?boundary=nearby(${latitude},${longitude},1000)&page_size=${page_size}&page_index=${page_index}&key=${TENCENT_MAP_KEY}`,
        success: (res) => {
          const {
            statusCode,
            errMsg,
            data: { status },
          } = res;
          if (statusCode === 200 && status === 0 && errMsg === "request:ok") {
            res.data.data = res.data.data.sort(
              (a, b) => a._distance - b._distance
            );
            this.tableData = isClear
              ? res.data.data
              : [...this.tableData, ...res.data.data];
          }
        },
      });
    },
    handleSearchNearbyKeys(isClear = false, params) {
      const { value, region, policy } = params;
      uni.request({
        url: `https://apis.map.qq.com/ws/place/v1/suggestion?keyword=${value}&region=${region}&policy=${policy}&key=${TENCENT_MAP_KEY}`,
        success: (res) => {
          const {
            statusCode,
            errMsg,
            data: { status },
          } = res;
          if (statusCode === 200 && status === 0 && errMsg === "request:ok") {
            res.data.data = res.data.data.sort(
              (a, b) => a._distance - b._distance
            );
            this.tableData = isClear
              ? res.data.data
              : [...this.tableData, ...res.data.data];
          }
        },
      });
    },
  },
};
</script>

<style scoped lang="scss">
.nearby-list {
  height: calc(
    100vh - 84rpx - 537rpx - 108rpx - 182rpx - env(safe-area-inset-bottom)
  );
  &-item {
    padding: 32rpx 33rpx;
    display: flex;
    align-items: center;
    border-bottom: 1rpx solid #ececec;
    &-left {
      flex: 1;
      .left-title {
        font-size: 32rpx;
        font-weight: 500;
        color: #181818;
      }
      .left-content {
        margin-top: 19rpx;
        font-size: 29rpx;
        font-weight: 500;
        color: #888888;
      }
    }
    &-right {
    }
  }
}
</style>
